package com.yumeko.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import uitl.RpcRequest;

import java.lang.reflect.Method;

/**
 * @program: netty-dubbo-zhenghao
 * @description:
 * @author: Zheng Hao
 * @create: 2020-03-12 14:18
 */
@Component
public class UserServerHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {
    private RpcRequest rpcRequest;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(StringUtils.isEmpty(rpcRequest));
        if (msg instanceof RpcRequest) {
            rpcRequest = (RpcRequest) msg;
            String name = rpcRequest.getClassName();
            String str = name.substring(0, name.indexOf("."));
            // 截取逗号后的字符串
            String classname = name.substring(str.length() + 1, name.length());
            String methodName = rpcRequest.getMethodName();
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
            Object[] parameters = rpcRequest.getParameters();
            Object bean = UserServerHandler.getBean(classname);
            Method method = bean.getClass().getMethod(methodName, parameterTypes);
            String result = (String) method.invoke(bean, parameters);
            rpcRequest.setResult(result);
            ctx.writeAndFlush(rpcRequest);
        }
    }

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        UserServerHandler.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public static Object getBean(Class c) {
        return applicationContext.getBean(c);
    }
}
